package com.yefcion.survey.util;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

@Slf4j
public class XuFileUtils {

    /**
     * 从文件中读取文本到 List<String>
     */
    @SneakyThrows
    public static List<String> readTxtFromFile(String srcFilePathName) {
        Path path = Paths.get(srcFilePathName);
        return Files.readAllLines(path);
    }

    /**
     * 将 List<String> 写入本地文本
     */
    @SneakyThrows
    public static void writeListToTxt(List<String> txts, String dstFilePathName) {
        Path path = Paths.get(dstFilePathName);

        for (int i = 0; i < txts.size(); i++) {
            if (i == 0) {
                Files.write(path, txts.get(i).getBytes());
            } else {
                try (BufferedWriter writer = Files.newBufferedWriter(path, StandardOpenOption.APPEND)) {
                    writer.write("\n" + txts.get(i));
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}
